.TH std::get_if(std::variant) 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::get_if(std::variant) \- std::get_if(std::variant)

.SH Synopsis
   Defined in header <variant>
   template< std::size_t I, class... Types >

   constexpr std::add_pointer_t<std::variant_alternative_t<I,
   std::variant<Types...>>>

       get_if( std::variant<Types...>* pv ) noexcept;
   template< std::size_t I, class... Types >

   constexpr std::add_pointer_t<const
   std::variant_alternative_t<I, std::variant<Types...>>>
                                                                \fB(1)\fP (since
       get_if( const std::variant<Types...>* pv ) noexcept;         C++17)
   template< class T, class... Types >

   constexpr std::add_pointer_t<T>

       get_if( std::variant<Types...>* pv ) noexcept;                      \fB(2)\fP (since
   template< class T, class... Types >                                         C++17)

   constexpr std::add_pointer_t<const T>

       get_if( const std::variant<Types...>* pv ) noexcept;

   1) Index-based non-throwing accessor: If pv is not a null pointer and pv->index() ==
   I, returns a pointer to the value stored in the variant pointed to by pv. Otherwise,
   returns a null pointer value. The call is ill-formed if I is not a valid index in
   the variant.
   2) Type-based non-throwing accessor: Equivalent to \fB(1)\fP with I being the zero-based
   index of T in Types.... The call is ill-formed if T is not a unique element of
   Types....

.SH Parameters

   I    - index to look up
   Type - unique type to look up
   pv   - pointer to a variant

.SH Return value

   Pointer to the value stored in the pointed-to variant or null pointer on error.

.SH Example


// Run this code

 #include <iostream>
 #include <variant>

 int main()
 {
     auto check_value = [](const std::variant<int, float>& v)
     {
         if (const int* pval = std::get_if<int>(&v))
             std::cout << "variant value: " << *pval << '\\n';
         else
             std::cout << "failed to get value!" << '\\n';
     };

     std::variant<int, float> v{12}, w{3.f};
     check_value(v);
     check_value(w);
 }

.SH Output:

 variant value: 12
 failed to get value!

.SH See also

   get(std::variant) reads the value of the variant given the index or the type (if the
   \fI(C++17)\fP           type is unique), throws on error
                     \fI(function template)\fP

.SH Category:
     * Uses of dcl rev begin with nonempty note
